<template>
<div class="page">
  <!--顶部-->
  <div style="text-align: center;">
    <div style="height: auto;display: inline-block;position: absolute;left: 100px;top: 20px;">
      <img src="../../../static/img/format.png" class="autImg" style="cursor: pointer;" @click="showPlayTable=false">
      <span style="font-size: 30px;cursor: pointer;" class="text" @click="showPlayTable=false">Cloudmusic</span>
    </div>
    <el-input v-model="songName" prefix-icon="el-icon-search" placeholder="搜索音乐" @keydown.enter.native="bzqllSearch" style="margin: 20px 0;width: 470px;"></el-input>
    <img :src="myInfo.myPortrait" class="autImg avatar" style="vertical-align: middle;margin-left: 20px;">
    <span class="text myName">{{myInfo.myName}}
    <i class="el-icon-refresh changeUser" title="更换用户" @click="changeUser"></i></span>
  </div>
  <!--歌曲列表-->
  <div class="data-table" v-if="showPlayTable">
    <el-table :data="songList" highlight-current-row stripe style="max-width: 1000px" :show-header="notShow">
      <el-table-column prop="pic" label="专辑图" width="200">
        <template slot-scope="scope">
          <div class="picImage" @click="playMusic(scope.$index)" :style="'background-image: url('+scope.row.pic+');'">
          </div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="title" label="歌曲名" width="230"></el-table-column>
      <el-table-column prop="author" label="作者" width="230"></el-table-column>
      <el-table-column prop="special" label="专辑" width="260"></el-table-column>
       <el-table-column label="播放" width="80">
         <template slot-scope="scope">
           <i class="iconfont" :class="scope.row.isPlaying?'big-icon-test1':'big-icon-test2'" style="font-size: 26px;" @click="playMusic(scope.$index)"></i>
         </template>
       </el-table-column>
    </el-table>
    <!--<div>
    <el-pagination
      layout="prev, pager, next"
      :total="50">
    </el-pagination>
    </div>-->
  </div>
  <!--歌单列表-->
  <div style="width: 950px;margin: 0 auto;transition: all 300ms ease-in-out;" v-else>
    <div style="font-size: 18px;padding: 10px 10px 10px 0;border-bottom: 2px solid #d92c2a;">我的歌单{{'('+mysongList.length+')'}}</div>
    <div class="mySongListImg" v-for="(item, index) in mysongList" :key="index" :style="'background-image: url('+item.songListImg+')'">
      <div class="mySongListImgBtn" @click="getMySongList(item.songListId)" @mouseover="showPlay(index)" @mouseout="hidePlay(index)">
        <!--<div class="sheDown" :style="`opacity:${item.isShow?'0.7':'0'};`"></div>-->
        <!--<img src="../../../static/img/play-white.png" width="60px" height="60px" :style="item.isShow?'':'display: none;'" @click="getMySongList(item.songListId)">-->
      </div>
      <div class="mySongListImgOp">
        <el-tooltip :content="item.songListName" placement="bottom" v-if="item.songListName.length>7">
          <span>{{item.songListName}}</span>
        </el-tooltip>
        <span v-else>{{item.songListName}}</span>
        <i class="iconfont big-icon-test2" style="float: right;" @click="playSongList(item.songListId)"></i>
      </div>
    </div>
  </div>
  <!--播放器-->
  <Playing  ref="Playing" :playingList="PlayingList" :list="PlayingData" :playFun="playMusic"></Playing>
</div>
</template>

<script>
import Playing from './Playing'
import songList from './songList'
import Storage from '../../util/StorageUtil.js'
export default {
  name: 'Cloudmusic',
  data () {
    return {
      myInfo: { // 我的信息
        myId: '',
        myPortrait: '', // 头像url
        myName: Storage.get('myName') || '僚机555'
      },
      isSearch: false, // 用于判断歌单是否是搜索出的结果
      mysongList: [], // 我的歌单
      songName: '', // 搜索的歌曲名字
      songList: [], // 搜索出的歌单
      notShow: false,
      isPlaying: false,
      PlayingData: [], // 正在播放的歌曲信息
      PlayingList: [], // 播放列表
      showPlayTable: false,
      controlIndex: 0,
      Interval: ''
    }
  },
  components: {
    Playing,
    songList
  },
  mounted () {
    // this.searchMySongListId()
    this.getMyInfo(this.myInfo.myName)
  },
  methods: {
    playSongList (id) {
      this.isSearch = true
      this.getMySongList(id, true)
    },
    changeUser () {
      this.$prompt('', '输入您的网易云昵称', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (!value) value = '僚机555'
        this.getMyInfo(value)
      }).catch(() => {

      })
    },
    getMyInfo (name) {
      // const url = `https://api.imjad.cn/cloudmusic/?type=search&search_type=1002&s=`
      const url = `https://api.bzqll.com/music/netease/search?key=579621905&s=${name}&type=user&limit=20&offset=0`
      this.$get(url, {}).then(response => {
        let data = response.data.userprofiles[0]
        for (let i = 0; i < response.data.userprofiles.length; i++) {
          if (response.data.userprofiles[i].nickname === name) {
            data = response.data.userprofiles[i]
          }
        }
        let birthday = this.common.format(data.birthday)
        let item = {
          myId: data.userId,
          myPortrait: data.avatarUrl,
          myBirthday: birthday,
          myName: data.nickname
        }
        this.myInfo = item
        Storage.set('myName', item.myName)
        this.searchMySongList(data.userId)
        // console.log(item)
      }).catch(() => {
        // 失败了, 更新数据(失败)
      }).finally(() => {
      })
    },
    getMySongList (id, isPlay) {
      // const url = `https://api.imjad.cn/cloudmusic/?type=playlist&id=${id}`
      const url = `https://api.bzqll.com/music/netease/songList?key=579621905&id=${id}`
      this.$get(url, {}).then(response => {
        this.isSearch = false
        // console.log(response)
        let data = response.data.songs
        // console.log(data)
        this.songList = []
        for (let i = 0; i < data.length; i++) {
          this.songList.push({
            pic: data[i].pic,
            author: data[i].singer,
            title: data[i].name,
            special: `《----》`,
            songId: data[i].id || data[i].Id,
            playUrl: `http://music.163.com/song/media/outer/url?id=${data[i].id || data[i].Id}.mp3`,
            showImg: false,
            isPlaying: false
          })
        }
        if (isPlay) {
          this.playMusic(0)
        }
        // for (let i = 0; i < this.songList.length; i++) {
        //   setTimeout(this.getSongAl(this.songList[i].songId, i), 300)
        // }
        // this.Interval = setInterval(this.getSongAl(this.songList[this.controlIndex].songId, this.controlIndex), 300)
        this.getSongAl(this.songList[0].songId, -1)
        this.showPlayTable = true
        // console.log(this.songList)
        // this.mySongList.push(item)
        // console.log(item)
      }).catch(() => {
        // 失败了, 更新数据(失败)
      }).finally(() => {
      })
    },
    getSongAl (id, index) {
      if (index === -1) {
        let that = this
        this.Interval = setInterval(function () {
          if (that.songList.length === that.controlIndex) {
            that.controlIndex = 0
            clearInterval(that.Interval)
            return
          }
          that.getSongAl(that.songList[that.controlIndex].songId, that.controlIndex)
          that.controlIndex++
        }, 100)
        return
      }
      if (this.songList.length === this.controlIndex) {
        clearInterval(this.Interval)
        return
      }
      const url = `https://api.imjad.cn/cloudmusic/?type=detail&id=${id}`
      this.$get(url, {}, false).then(response => {
        // 成功了, 更新数据(成功)
        var data = response.songs[0].al.name
        // console.log(data)
        this.songList[index].special = `《${data}》`
        // this.songList[index].time = this.common.formatSeconds(response.songs[0].dt)
      }).catch(() => {
        // 失败了, 更新数据(失败)
      }).finally(() => {
      })
    },
    searchMySongList (id) {
      // const url = `https://api.imjad.cn/cloudmusic/?type=search&search_type=1000&s=${name}`
      const url = `https://api.bzqll.com/music/netease/userSongList?key=579621905&uid=${id}`
      this.$get(url, {}).then(response => {
        let data = response.data
        let item = []
        for (let i = 0; i < data.length; i++) {
          item.push({
            songListId: data[i].id,
            songListName: data[i].title,
            songListImg: data[i].coverImgUrl,
            playCount: data[i].playCount,
            isShow: false
          })
          // this.getMySongList(response.result.playlists[i].id)
        }
        this.mysongList = item
        /* this.myInfo.myId = response.result.playlists[0].userId
        let item = []
        console.log(item) */
        // this.songListId = item
      }).catch(() => {
        // 失败了, 更新数据(失败)
      }).finally(() => {
      })
    },
    bzqllSearch () {
      const url = `https://api.bzqll.com/music/netease/search?key=579621905&s=${this.songName}&type=song&limit=10&offset=0`
      this.$get(url, {}).then(response => {
        this.isSearch = true
        // 成功了, 更新数据(成功)
        var item = []
        for (let i = 0; i < response.data.length; i++) {
          item.push({
            songId: response.data[i].id,
            playUrl: response.data[i].url,
            author: response.data[i].singer
          })
        }
        this.songList = []
        for (let j = 0; j < item.length; j++) {
          this.getCloudmusic('detail', item[j])
        }
      }).catch(() => {
        // 失败了, 更新数据(失败)
      }).finally(() => {
      })
    },
    search () {
      const url = `https://api.apiopen.top/searchMusic?name=${this.songName}`
      this.$get(url, {}).then(response => {
        this.isSearch = true
        // 成功了, 更新数据(成功)
        var item = []
        for (let i = 0; i < response.result.length; i++) {
          item.push({
            songId: response.result[i].songid,
            playUrl: response.result[i].url
          })
        }
        this.songList = []
        for (let j = 0; j < item.length; j++) {
          this.getCloudmusic('detail', item[j].songId, item[j].playUrl)
        }
      }).catch(() => {
        // 失败了, 更新数据(失败)
      }).finally(() => {
      })
    },
    getCloudmusic (type, data, songer) {
      const url = `https://api.imjad.cn/cloudmusic/?type=${type}&id=${data.songId}&br=128000`
      this.$get(url, {})
        .then(response => {
          // 成功了, 更新数据(成功)
          // console.log(response)
          // this.sonList = response.result
          let item = response.songs[0]
          item.ar[0].name = data.author
          this.setSongList(item)
        })
        .catch(() => {
          // 失败了, 更新数据(失败)
        }).finally(() => {
        })
    },
    setSongList (item) {
      this.songList.push({
        // 专辑图
        pic: item.al.picUrl,
        // 作者
        author: item.ar[0].name,
        // 歌名
        title: item.name,
        // 专辑名
        special: `《${item.al.name}》`,
        // 歌曲Id
        songId: item.id || item.Id,
        // 播放地址
        playUrl: `http://music.163.com/song/media/outer/url?id=${item.id || item.Id}.mp3`,
        // 是否显示
        showImg: false,
        // 是否正在播放
        isPlaying: false
        // time: this.countTime(item.dt)
      })
      this.showPlayTable = true
      // console.log(this.songList)
    },
    countTime (time) {
      // console(time)
      return '4:47'
    },
    showPlay (index) {
      // console.log(index)
      for (let i = 0; i < this.mysongList.length; i++) {
        this.mysongList[i].isShow = false
      }
      this.mysongList[index].isShow = true
    },
    hidePlay (index) {
      this.mysongList[index].isShow = false
    },
    playMusic (index, loop) {
      let audio = this.$refs.Playing.audio
      this.isPlaying = true
      // if (this.$refs.Playing.planLength === this.$refs.Playing.List.Second && !this.songList[index].isPlaying) {
      //   this.newPlay(index)
      //   return
      // }
      // 是否正在播放
      if (this.songList[index].isPlaying) {
        // 暂停
        audio.pause()
        // 当前行状态设为暂停状态
        this.songList[index].isPlaying = false
        this.$refs.Playing.inPlayData.isPlaying = false
        this.PlayingList.isPlaying = false
      } else {
        // 将其他行设置为暂停状态
        for (let i = 0; i < this.songList.length; i++) {
          this.songList[i].isPlaying = false
        }
        this.songList[index].isPlaying = true
        // 如果audio有正在播放的歌曲
        if (this.$refs.Playing.playUrl === this.songList[index].playUrl) {
          // 播放
          audio.play()
        } else {
          // 将新的url交给audio去播放
          this.$refs.Playing.playUrl = this.songList[index].playUrl
          let that = this
          if (loop) audio.load()
          if (this.isSearch) {
            // that.PlayingList.push(that.songList[index])
            that.PlayingList = that.$refs.Playing.inPlayList
            let is = false
            let PlayingListIndex = -1
            for (let i = 0; i < that.$refs.Playing.inPlayList.length; i++) {
              if (that.$refs.Playing.inPlayList[i].songId == that.songList[index].songId) { //eslint-disable-line
                is = true
                PlayingListIndex = i
              }
            }
            // if (!is) that.PlayingList.push(that.songList[index])
            if (is) {
              that.$refs.Playing.jumpPlayList(PlayingListIndex)
              return
            } else {
              that.PlayingList.push(that.songList[index])
            }
          } else {
            that.PlayingList = that.songList
          }
          that.PlayingData = that.songList[index]
          that.PlayingData.index = index
          that.PlayingData.isPlaying = false
          Storage.set('playList', JSON.stringify(that.PlayingList))
          that.$refs.Playing.playList = that.PlayingList
          that.$refs.Playing.inPlayList = that.PlayingList
          that.$refs.Playing.inPlayData = that.PlayingData
          console.log(that.PlayingData)
          Storage.set('PlayingData', JSON.stringify(that.PlayingData))
          // 当前歌曲时间
          // that.songList[index].Second = parseInt(audio.duration)
          // 监听audio是否加载完毕，如果加载完毕，则读取audio播放时间
          /* audio.addEventListener(`canplay`, function () {
            // document.getElementById('audio_length_total').innerHTML = transTime(audio.duration)
            console.log('加载完毕', that.common.formatSeconds(audio.duration), parseInt(audio.duration))
            // 加载完歌曲后给子组件赋值 开始播放
          }) */
        }
      }
    },
    newPlay (index) {
      this.$refs.Playing.playUrl = ''
      this.$refs.Playing.planLength = 0
      this.playMusic(index, true)
    },
    jump (num) {
      let audio = this.$refs.Playing.audio
      audio.currentTime = num
    }
  },
  watch: {
    songList (value) {
      console.log(value)
      if (this.PlayingData) {
        for (let i = 0; i < value.length; i++) {
          if (value[i].songId === this.$refs.Playing.inPlayData.songId) {
            this.songList[i].isPlaying = true
          }
        }
      }
    }
  }
}
</script>

<style scoped>
  .page{
    overflow: auto;
    background-color: #f5f5f5;
    height: 100%;
    padding-bottom: 55px;
    /*position: fixed;*/
    /*bottom: 50px;*/
    width: 100%;
  }
  .data-table{
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    /*transition: margin 300ms ease-in-out;*/
  }
  .picImage{
    background-size: cover;
    width: 60px;
    height: 60px;
    display: inline-block;
  }
  .mySongListImg{
    background-size: cover;
    width: 140px;
    height: 140px;
    margin: 20px 25px;
    display: inline-block;
  }
  .mySongListImgBtn{
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    height:113px;
    width: 100%;
    cursor: pointer;
    background: url('https://s2.music.126.net/style/web2/img/coverall.png?4fd1c0ba8740d4c98e14a05948bb3c27') no-repeat 0 0;
  }
  .mySongListImgBtn img{
    position: absolute;
    z-Index:9999;
    cursor: pointer;
  }
  .sheDown{
    background: black;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: 99;
    transition: opacity 300ms ease-in-out;
  }
  .mySongListImgOp{
    display: flex;
    align-items: center;
    height:27px;
    color: #ccc;
    font-family: sans-serif;
    padding: 0 10px;
    background: url('https://s2.music.126.net/style/web2/img/coverall.png?4fd1c0ba8740d4c98e14a05948bb3c27') no-repeat 0 -537px;
  }
  .mySongListImgOp i:hover{
    color: white;
  }
  .mySongListImgOp span{
    width: 90%;
    font-size: 14px;
    overflow: hidden;/*超出部分隐藏*/
    text-overflow:ellipsis;/* 超出部分显示省略号 */
    white-space: nowrap;/*规定段落中的文本不进行换行 */
  }
  .picImageMin{
    width: 60px;
    height: 60px;
    display: inline-block;
    animation: all 300ms ease-in-out;
    position: absolute;
  }
  .picImage,.big-icon-test2,.big-icon-test1:hover{
    cursor: pointer;
  }
  .autImg{
    width: 36px;
    height: 36px;
    vertical-align: sub;
  }
  .avatar{
    border-radius: 50%;
    border: 1px solid #d92c2a;
  }
  .text{
    font-family: sans-serif;
    display: inline-block;
  }
  .myName{
    transition: all 180ms ease-in-out;
    cursor: default;
  }
  .myName:hover{
    color: #d92c2a;
    cursor: default;
  }
  .myName:hover .changeUser{
    opacity: 1;
  }
  .changeUser{
    opacity: 0;
    color: #d92c2a;
    cursor: pointer;
    transition: all 180ms ease-in-out;
  }
</style>
